<template>
  <!-- v-if="songInfo.src" -->
  <div
    class="mainPage"
    v-if="songInfo[0]"
    :class="isDrawer ? 'drawer' : this.$route.meta.isPlayer ? 'isPlayer' : ''"
    ref="MainRef"
  >
    <aplayer
      class="a-player"
      ref="aplayer"
      :autoplay="autoplay"
      :music="songInfo[0]"
      :list="songInfo"
      :showLrc="showLrc"
      :mutex="mutex"
      :theme="theme"
      :shuffle="shuffle"
      :repeat="repeat"
      :listFolded="listFolded"
      :listMaxHeight="listMaxHeight"
      :controls="controls"
      :muted="muted"
      :volume="volume"
      :preload="preload"
      @listShow="handleEvent"
      @listHide="handleEvent"
      @ended="handleEvent"
      @play="handleEvent"
      @pause="handleEvent"
      @listSwitch="handleEvent"
      fixed
    ></aplayer>
    <!-- :list="playList" -->
    <!-- {{ songInfo[0] }} -->
  </div>
</template>

<script>
import { mapGetters, mapMutations, mapActions } from "vuex"
import aplayer from "vue-aplayer"
export default {
  props: {
    /**
     *  音频配置
     * */
    // playInfo: {
    //   type: Object,
    //   default: () => {
    //     return {
    //       title: "", //歌曲名称
    //       artist: " ", //演唱者
    //       lrc: "", //LRC 歌词或者歌词文件的 URL
    //       pic: "", //封面图片 URL
    //       src: "", //音频文件的 URL
    //       id: "",
    //     };
    //   },
    // },
    /**
     *  播放列表。如果 list 不是空数组，播放列表就会显示出来，即使 list 中只有一首歌并且它和 music 一样
     * */
    // list: {
    //   type: Array,
    //   default: () => {
    //     return [];
    //   },
    // },
    /**
     *  是否展示歌词
     * */
    showLrc: {
      type: Boolean,
      default: true,
    },
    /**
     *  自动播放。如果多个 mutex 播放器设置了 autoplay，只有第一个会自动播放
     * */
    autoplay: {
      type: Boolean,
      default: false,
    },
    /**
     *  显示原生 audio 元素（在播放器面板和播放列表面板之间）
     * */
    controls: {
      type: Boolean,
      default: false,
    },
    /**
     *  静音
     * */
    muted: {
      type: Boolean,
      default: false,
    },
    /**
     *  是否在该播放器播放时暂停其他播放器
     * */
    mutex: {
      type: Boolean,
      default: true,
    },
    /**
     *  随机播放
     * */
    shuffle: {
      type: Boolean,
      default: false,
    },
    /**
     *  默认收起播放列表
     * */
    listFolded: {
      type: Boolean,
      default: true,
    },
    /**
     *  主题色。如果当前歌曲也设置了 theme 则以歌曲的为准
     * */
    theme: {
      type: String,
      default: "#a1322c",
    },
    /**
     *  轮播模式。值可以是 'repeat-one'（单曲循环）'repeat-all'（列表循环）或者 'no-repeat'（不循环）。
     *  为了好记，还可以使用对应的 'music' 'list' 'none'
     * */
    repeat: {
      type: String,
      default: "repeat-all",
    },
    /**
     * 播放列表面板最大高度
     * */
    listMaxHeight: {
      type: String,
      default: "150px",
    },
    /**
     * 加载音乐的方式可以是“none”“metadata”或“auto”
     * */
    preload: {
      type: String,
      default: "metadata",
    },
    /**
     * 播放音量
     * */
    volume: {
      type: Number,
      default: 0.8,
    },
    isDrawer: {
      type: Boolean,
      default: false,
    },
    // isPlayer: {
    //   type: Boolean,
    //   default: false,
    // },
  },
  data() {
    return {
      songReady: false,
      id: "",
      musicUrl: "",
      songInfo: [], //当前播放单曲
      // list: [
      //   {
      //     title: "",
      //     artist: "",
      //     src: "",
      //     pic: "",
      //   }
      // ]
      // 防止点击进度条执行多次播放暂停
      prePause: true,
      prePlay: true,
    }
  },
  watch: {
    async currentSong(newSong, oldSong) {
      if (JSON.stringify(newSong) == "{}") {
        this.songInfo = []
        return
      } else if (!newSong.trackId) {
        // this.songInfo[0].src = "";
        return
      }
      // 检测用户权限
      let allow
      if (this.loginStatu) {
        let songParams = {
          token: this.userInfo.token,
          moduleId: newSong.musicAlbum.moduleId,
          contentId: newSong.trackId,
          reportFlag: newSong.trackId === oldSong.trackId ? 0 : 1,
        }
        // 检测用户权限
        allow = await this.$api.user.checkUserPermissions(songParams)
      } else {
        let songParams = {
          // token: this.userInfo.token,
          moduleId: newSong.musicAlbum.moduleId,
          contentId: newSong.trackId,
          reportFlag: newSong.trackId === oldSong.trackId ? 0 : 1,
        }
        // 检测用户权限
        allow = await this.$api.user.checkUserPermissionsByIp(songParams)
      }
      if (allow.code === 1000000) {
        // if (this.userInfo.hasOwnProperty('modules')){
        //   alert("__")
        // }
        // if (newSong.musicAlbum.moduleId)
        // !newSong.trackId || newSong.trackId === oldSong.trackId
        // this.list = this.playList.map((i) => {
        //   return {
        //     title:
        //       this.$i18n.locale === "zh"
        //         ? i.trackCtitle || i.trackTitle
        //         : i.trackTitle,
        //     artist: i.composer ? (i.composer.map((x) => {
        //       if (this.$i18n.locale === "zh" && x.fullCname) {
        //         return x.fullCname;
        //       } else {
        //         return x.fullName;
        //       }
        //     })).join("  ") : "无", //演唱者
        //     lrc: "", //LRC 歌词或者歌词文件的 URL
        //     pic: i.musicAlbum.cover500, //封面图片 URL
        //     src: "", //音频文件的 URL
        //   }
        // })
        let music = { title: "", artist: "", src: "", pic: "" }
        // this.songInfo[0].src = "";
        this.songReady = false
        this.canLyricPlay = false
        // if (this.currentLyric) {
        //   this.currentLyric.stop()
        //   // 重置为null
        //   this.currentLyric = null
        //   this.currentTime = 0
        //   this.playingLyric = ''
        //   this.currentLyricNum = 0
        // }
        // let composer = []; // 人物集
        if (newSong.composer) {
          let composer = newSong.composer.map((i) => {
            if (this.$i18n.locale === "zh" && i.fullCname) {
              return i.fullCname
            } else {
              return i.fullName
            }
          })
          music.artist = composer.join("  ")
        } else {
          music.artist = " "
        }
        // this.$nextTick(async () => {
        let params = {
          trackId: newSong.trackId,
          quality:
            newSong.hifi >= 1
              ? "hifi"
              : newSong.kbps320 >= 1
              ? "320"
              : newSong.kbps192 >= 1
              ? "192"
              : newSong.kbps64
              ? "64"
              : "",
          terminal: "Web",
        }
        music.pic = newSong.musicAlbum.cover500
        music.title =
          this.$i18n.locale === "zh"
            ? newSong.trackCtitle || newSong.trackTitle
            : newSong.trackTitle
        if (newSong.trackId !== oldSong.trackId) {
          let res = await this.$api.user.musicAddress(params)
          music.src = res.data
          // this.songInfo[0] = music;
          // console.log(this.$refs.player)
          // (this.id = newSong.trackId);
          // music.id = newSong.trackId;
          // console.log(music)
          this.$set(this.songInfo, 0, music)
          //登录状态 - 添加播放记录
          if (this.loginStatu) {
            await this.$api.user.addPlayRecord({ contentId: newSong.trackId })
          }
        }
        // });
        setTimeout(() => {
          this.$refs.aplayer.play()
        }, 120)
      } else if (allow.code === 1701101) {
        this.playStatus(false)
        this.$notify({
          title: this.$t("public.warning"),
          message: this.$t("public.accountNotExist"),
          type: "warning",
          offset: 100,
        })
      } else if (allow.code === 1701102) {
        this.playStatus(false)
        this.$notify({
          title: this.$t("public.warning"),
          message: this.$t("public.validityExpired"),
          type: "warning",
          offset: 100,
        })
      } else if (allow.code === 1701103) {
        this.playStatus(false)
        this.$notify({
          title: this.$t("public.warning"),
          message: this.$t("public.organizationValidityExpires"),
          type: "warning",
          offset: 100,
        })
      } else if (allow.code === 1701104) {
        this.playStatus(false)
        this.$notify({
          title: this.$t("public.warning"),
          message:
            newSong.musicAlbum.moduleId == 516
              ? this.$t("public.classicalValidityExpires")
              : newSong.musicAlbum.moduleId == 518
              ? this.$t("public.worldNationValidityExpires")
              : newSong.musicAlbum.moduleId == 580
              ? this.$t("public.JazzValidityExpires")
              : newSong.musicAlbum.moduleId == 517
              ? this.$t("public.audioBooksValidityExpires")
              : this.$t("public.moduleValidityExpires"),
          type: "warning",
          offset: 100,
        })
      } else if (allow.code === 1000001) {
        this.playStatus(false)
        this.$notify({
          title: this.$t("public.warning"),
          message: this.$t("public.loginPermission"),
          type: "warning",
          offset: 100,
        })
      } else if (allow.code === 1701201 || allow.code === 1701105) {
        this.setDialogLogin(true)
        this.playStatus(false)
      } else {
        this.playStatus(false)
      }
    },
    // songInfo(newSong) {
    //   console.log(newSong)
    // },
    // // 监听播放状态
    playing(isPlaying) {
      // if (!this.songReady) {
      //   return
      // }
      // setTimeout(() => {
      const audio = this.$refs.aplayer
      if (audio) {
        isPlaying ? audio.play() : audio.pause()
      }
      // }, 220);
    },
    // playList(newList, oldlist){
    //   newList.map((item)=>{
    //     return {
    //       title: this.$i18n.locale === 'zh' ? item.trackCtitle||item.trackTitle : item.trackTitle,
    //       artist: composer.join("  "),
    //     }
    //   })
    // }
  },
  computed: {
    ...mapGetters([
      "loginStatu",
      "userInfo",
      "playList",
      "currentSong",
      "playing",
      "currentIndex",
    ]),
    // list() {
    //   return this.playList.map((i) => {
    //     return {
    //       title:
    //         this.$i18n.locale === "zh"
    //           ? i.trackCtitle || i.trackTitle
    //           : i.trackTitle,
    //       artist: (i.composer.map((x) => {
    //         if (this.$i18n.locale === "zh" && x.fullCname) {
    //           return x.fullCname;
    //         } else {
    //           return x.fullName;
    //         }
    //       })).join("  "), //演唱者
    //       lrc: "", //LRC 歌词或者歌词文件的 URL
    //       pic: i.musicAlbum.cover500, //封面图片 URL
    //       src: "", //音频文件的 URL
    //       id: i.trackId,
    //       quality:
    //         i.hifi == 1
    //           ? "hifi"
    //           : i.kbps320 == 1
    //           ? "320"
    //           : i.kbps192 == 1
    //           ? "192"
    //           : i.kbps64
    //           ? "64"
    //           : "",
    //     }
    //   })
    // }
  },
  created() {},
  // async mounted() {
  //   await this.init();

  // },
  methods: {
    ...mapMutations({
      setPlayingState: "SET_PLAYING_STATE",
      setCurrentIndex: "SET_CURRENT_INDEX",
      setPlayList: "SET_PLAYLIST",
      setDrawer: "SET_DRAWER",
      setDialogLogin: "SET_DIALOGLOGIN",

      // setPlayParentId: "SET_PLAY_PARENT_ID",
    }),
    ...mapActions([
      "saveHistoryList",
      "deleteHistoryList",
      "clearHistoryList",
      "selectPlay",
      "playStatus",
    ]),
    // 播放事件
    async handleEvent(e) {
      if (e.type == "play") {
        let aplayerList = document.getElementsByClassName("aplayer-icon-menu")
        // aplayerList[0].className.indexOf("inactive") != -1
        if (aplayerList) {
          aplayerList[0].addEventListener("click", this.dbPlayList)
        }
        // if (this.$refs.aplayer.currentMusic.id) {
        //   // 检测用户权限
        //   let songParams = {
        //     token: this.userInfo.token,
        //     moduleId: this.$refs.aplayer.currentMusic.moduleId,
        //     contentId: this.$refs.aplayer.currentMusic.id,
        //   };
        //   // 检测用户权限
        //   let allow = await this.$api.user.checkUserPermissions(songParams);
        //   if (allow.code === 1000000) {
        //     let params = {
        //       trackId: this.$refs.aplayer.currentMusic.id,
        //       quality: this.$refs.aplayer.currentMusic.quality,
        //       terminal: "Web",
        //     };
        //     let res = await this.$api.user.musicAddress(params);
        //     this.$set(this.$refs.aplayer.currentMusic, "src", res.data);
        //     // setTimeout(() => {
        //     //   this.$refs.aplayer.play();
        //     // }, 120);
        //     if (this.loginStatu) {
        //       await this.$api.user.addPlayRecord({
        //         contentId: this.$refs.aplayer.currentMusic.id,
        //       });
        //     }
        //   } else if (allow.code === 1701101) {
        //     this.playStatus(false);
        //     this.$notify({
        //       title: this.$t("public.warning"),
        //       message: this.$t("public.accountNotExist"),
        //       type: "warning",
        //       offset: 100,
        //     });
        //   } else if (allow.code === 1701102) {
        //     this.playStatus(false);
        //     this.$notify({
        //       title: this.$t("public.warning"),
        //       message: this.$t("public.validityExpired"),
        //       type: "warning",
        //       offset: 100,
        //     });
        //   } else if (allow.code === 1701103) {
        //     this.playStatus(false);
        //     this.$notify({
        //       title: this.$t("public.warning"),
        //       message: this.$t("public.organizationValidityExpires"),
        //       type: "warning",
        //       offset: 100,
        //     });
        //   } else if (allow.code === 1701104) {
        //     this.playStatus(false);
        //     this.$notify({
        //       title: this.$t("public.warning"),
        //       message:
        //         this.$refs.aplayer.currentMusic.moduleId == 516
        //           ? this.$t("public.classicalValidityExpires")
        //           : this.$refs.aplayer.currentMusic.moduleId == 518
        //           ? this.$t("public.worldNationValidityExpires")
        //           : this.$refs.aplayer.currentMusic.moduleId == 580
        //           ? this.$t("public.JazzValidityExpires")
        //           : this.$refs.aplayer.currentMusic.moduleId == 517
        //           ? this.$t("public.audioBooksValidityExpires")
        //           : this.$t("public.moduleValidityExpires"),
        //       type: "warning",
        //       offset: 100,
        //     });
        //   }
        //   // this.setCurrentIndex(this.list.findIndex((item)=>{
        //   //   return item.id == this.$refs.aplayer.currentMusic.id
        //   // }))
        // } else {
        //   // if ()
        // }
        if (this.prePlay) {
          this.prePlay = false
          this.playStatus(true)
          setTimeout(() => {
            this.prePlay = true
          }, 500)
        }
        // if (this.$refs.aplayer.currentMusic.src) {
        //   alert("111")
        // } else {

        // }
        // this.selectPlay({
        //   list: this.playList,
        //   index: this.currentSong.trackId,
        // });
      } else if (e.type == "pause") {
        if (this.prePause) {
          this.prePause = false
          this.playStatus(false)
          setTimeout(() => {
            this.prePause = true
          }, 500)
        }
      } else if (e.type == "ended") {
        if (this.$refs.aplayer.currentMusic.id == undefined) {
          this.nextSong()
        }
      } else if (e.type == "listSwitch") {
        console.log("切换单曲")
      }
      // console.log(e)
      // if (this.mode === playMode.loop) {
      //   this.loopSong()
      // } else {
      //   this.nextSong()
      // }
    },
    // audioplay() {
    //   console.log()
    // },
    dbPlayList() {
      if (this.isDrawer) {
        this.setDrawer(false)
      } else {
        this.setDrawer(true)
      }
    },
    // 下一首
    nextSong() {
      // if (!this.songReady) {
      //   return
      // }
      let index = this.currentIndex + 1
      // console.log(index, this.playList.length);
      if (index === this.playList.length) {
        index = 0
      }
      this.setCurrentIndex(index)
    },
  },
  components: {
    aplayer,
  },
  beforeDestroy() {},
}
</script>

<style lang="scss" scoped>
.mainPage {
  width: 100%;
  // height: 84px;
  background: #fcfcfc;
  min-height: 160px;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 9;
  display: none;
  box-shadow: 0 -4px 10px #f5f5f5;
  .a-player {
    width: 1200px;
    height: auto;
    margin: 20px auto;
  }
  // border: 1px solid #E0E0E0;
  // border-radius: 4px;
}
.drawer {
  display: block;
  z-index: 9998;
}
.isPlayer {
  display: block;
  z-index: 9998;
}
</style>
<style lang="scss">
.a-player {
  .aplayer-time {
    .aplayer-icon-mode {
      // &:not(last-child) {
      display: none;
      // }
    }
  }
  .aplayer-bar-wrap {
    .aplayer-loaded {
      width: 0% !important;
    }
  }
  .aplayer-list {
    display: none;
  }
}
</style>
